package com.cn.algorithm01;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author hels
 * @version 1.0
 * @date 2021/10/13 12:01
 * 通过单链表结构，手写队列和栈
 */
public class Code08_LinkedListToQueueAndStack {
    // 定义一个链表结构
    public static class Node<V> {
        public V value;
        public Node<V> next;

        public Node(V v){
            value = v;
        }
    }

    // 链表结构实现队列
    public static class MyQueue<V> {
        private Node<V> head;
        private Node<V> tail;
        private int size;

        public MyQueue() {
            head = null;
            tail = null;
            size = 0;
        }

        public boolean isEmpty() {
            return size == 0;
        }

        public int size() {
            return size;
        }

        public void offer(V value) {
            Node<V> node = new Node<V>(value);

            if (head == null) {
                head = node;
                tail = node;
            } else {
                tail.next = node;
                tail = node;
            }
            size++;
        }

        public V poll() {
            V ans = null;
            if (head != null) {
                ans = head.value;
                head = head.next;
                size--;
            }
            // 这个条件要后写，前面取走后再次进行判断是否为空，若是则将tial也指向null
            if (head == null) {
                tail = null;
            }
            return ans;
        }

        public V peek() {
            V ans = null;
            if (head != null) {
                ans = head.value;
            }
            return ans;
        }
    }

    // 通过单链表结构实现栈的功能，栈是先进后出
    public static class MyStack<V> {
        private Node<V> head;
        private int size;

        public MyStack(V v) {
            head = null;
            size = 0;
        }
        public boolean isEmpty() {
            return size == 0;
        }
        public int size() {
            return size;
        }

        // 在自定义栈中添加值（对象）
        public void push(V value) {
            Node<V> node = new Node<V>(value);

            if (head == null) {
                head = node;
            }
            if (head != null) {
                node.next = head;
                head = node;
            }
            size ++;
        }
        // 自定义栈中取值，取头值
        public V pop() {
            V ans = null;
            if (head != null) {
                ans = head.value;
                head =  head.next;
                size--;
            }
            return ans;
        }
        // 读取当前要取的值
        public V peek() {
//            V ans = null;
//            if (value != null) {
//                ans = value.value;
//            }
//            return ans;
            return head == null ? null : head.value;
        }

    }

    public static void main(String[] args) {
        Queue<Integer> queue = new LinkedList<Integer>();
    }






}
